package com.gz.moreaseManager.sys.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gz.moreaseManager.config.SelfUserDetails;
import com.gz.moreaseManager.core.modal.AjaxResult;
import com.gz.moreaseManager.core.modal.HttpCode;
import com.gz.moreaseManager.core.modal.PageResult;
import com.gz.moreaseManager.sys.entity.User;
import com.gz.moreaseManager.sys.service.IUserService;
import com.gz.moreaseManager.sys.transfer.SysUserVo;
import com.gz.moreaseManager.utils.DateUtil;
import com.gz.moreaseManager.utils.UtilTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;


/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author wike
 * @since 2019-02-19
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;


    /**
     * 返回用户列表界面
     * @return
     */
    @GetMapping("/list")
    public ModelAndView listPage(){
        return new ModelAndView("sys/userManage/list");
    }
    /**
     * 根据条件查询分页用户列表
     * @param userName
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/listPage")
    public PageResult<User> findAllUserPage(String userName, String tel,
                                            Integer roleId, Integer status,
                                            @DateTimeFormat(pattern = "yyyy-MM-dd")Date startDate,
                                            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                            Integer pageNum, Integer pageSize){

        //分页
        Page<User> paramsPage = new Page();
        paramsPage.setCurrent(pageNum);
        paramsPage.setSize(pageSize);
        //构建查询
        EntityWrapper wrapper = new EntityWrapper<User>();
        if( UtilTool.isNotBlank( userName ))
            wrapper.like("u.user_name",userName);
        if( UtilTool.isNotBlank( tel ))
            wrapper.like("u.user_phone",tel);
        if( UtilTool.isNotBlank( roleId ))
            wrapper.eq("r.role_id",roleId);
        if( UtilTool.isNotBlank( status ))
            wrapper.eq("u.status",status);
        if( UtilTool.isNotBlank( startDate ) ){
            if( UtilTool.isNotBlank( endDate ) && startDate.getTime() == endDate.getTime() ){
                wrapper.between("u.create_time",startDate,DateUtil.addDays(startDate,1));
            }else{
                wrapper.between("u.create_time",startDate,
                        UtilTool.isNotBlank(endDate)?DateUtil.addDays(endDate,1):DateUtil.addDays(new Date(),1));
            }
        }

        if( UtilTool.isBlank(startDate) && UtilTool.isNotBlank( endDate )){
            wrapper.le("u.create_time",DateUtil.addDays(endDate,1));
        }
        //排序
        wrapper.orderBy("u.create_time",false);

        Page<User> lists = userService.findUserListByParams(paramsPage,wrapper);
        return new PageResult<>(0, null, lists.getTotal(), lists.getRecords());
    }

    /**
     * 根据ID获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/findUserInfoByUserId")
    public AjaxResult<SysUserVo> findUserInfoByUserId(Integer userId ){
        SysUserVo sysUserInfo = userService.findUserInfoByUserId( userId );
        return AjaxResult.success(sysUserInfo);
    }

    /**
     * 刪除用戶
     * @param userId
     * @return
     */
    @PostMapping("/delUser")
    public AjaxResult<Boolean> delUser(Integer userId ){
        if( userId == null )
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        boolean flag = userService.deleteById(userId);
        return flag ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "删除用户信息失败!");
    }

    /**
     * 批量禁用用戶
     * @param userIds
     * @return
     */
    @PostMapping("/disableUser")
    public AjaxResult<Boolean> disableUser(Integer... userIds ){
        if( userIds == null )
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");
        boolean success = userService.disableUserBatch(userIds);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "禁用用户信息失败!");
    }

    /**
     * 批量启用用户
     * @param userIds
     * @return
     */
    @PostMapping("/enableUser")
    public AjaxResult<Boolean> enableUser(Integer ... userIds){
        if( userIds == null )
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");
        boolean success = userService.enableUserBatch(userIds);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "启用用户信息失败!");
    }

    /**
     * 新增用户接口
     * @param sysUserInfo
     * @return
     */
    @PostMapping("/addUser")
    public AjaxResult<Boolean> addUser(SysUserVo sysUserInfo){
        if (sysUserInfo == null
                || UtilTool.isBlank(sysUserInfo.getUserName())
                || UtilTool.isBlank(sysUserInfo.getUserPhone()))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");
        //判断当前用户已经存在
        Wrapper wrapper = new EntityWrapper<User>();
        wrapper.eq("user_name",sysUserInfo.getUserName());
        User userOldVo = userService.selectOne( wrapper );
        if( UtilTool.isNotBlank( userOldVo ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "用户名称已使用!");
        //判断当前用户已经存在
        Wrapper wrapper1 = new EntityWrapper<User>();
        wrapper1.eq("user_phone",sysUserInfo.getUserPhone());
        User userOldVo1 = (User)userService.selectOne( wrapper1 );
        if( UtilTool.isNotBlank( userOldVo1 ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "手机号码已占用!");


        boolean success = userService.addUserInfo( sysUserInfo );
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "添加用户信息失败!");

    }

    /**
     * 修改用户接口
     * @param sysUserInfo
     * @return
     */
    @PostMapping("/editUser")
    public AjaxResult<Boolean> editUser(SysUserVo sysUserInfo){
        if (sysUserInfo == null
                || UtilTool.isBlank(sysUserInfo.getUserName())
                || UtilTool.isBlank(sysUserInfo.getUserId()))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        //判断当前用户已经存在
        Wrapper wrapper = new EntityWrapper<User>();
        wrapper.eq("user_name",sysUserInfo.getUserName());
        wrapper.ne("user_id",sysUserInfo.getUserId());
        User userOldVo = (User)userService.selectObj( wrapper );
        if( UtilTool.isNotBlank( userOldVo ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "用户名称已使用!");
        //判断当前用户已经存在
        Wrapper wrapper1 = new EntityWrapper<User>();
        wrapper1.eq("user_phone",sysUserInfo.getUserPhone());
        wrapper1.ne("user_id",sysUserInfo.getUserId());
        User userOldVo1 = (User) userService.selectOne( wrapper1 );
        if( UtilTool.isNotBlank( userOldVo1 ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "手机号码已占用!");
        boolean success = userService.updateUserInfo(sysUserInfo);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "修改用户信息失败!");
    }

    /**
     * 跳转到修改密码界面
     * @return
     */
    @GetMapping("/resetPass")
    public ModelAndView resetPass(Authentication authentication){
        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();

        return new ModelAndView("sys/userManage/resetPass","user",userDetails);
    }

    /**
     * 修改密码
     * @param userName
     * @param userPhone
     * @param oldPass
     * @param newPass
     * @return
     */
    @PostMapping("/changePass")
    public AjaxResult<Boolean> changePass(String userName,String userPhone,String oldPass,String newPass){

        if ( UtilTool.isBlank( userName )
                || UtilTool.isBlank( userPhone)
                || UtilTool.isBlank( oldPass )
                || UtilTool.isBlank( newPass ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        boolean success = userService.resetPassword( userName,userPhone,oldPass,newPass);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "修改密码失败!");
    }
}
